/**********************************************************************
 * 
 *
 * @url: /services/apexrest/rest
 * @data:
 *  {
        
    }
*************************************************************************/
@RestResource(urlMapping='/CRM/upsertUnTaskREST/*')
global with sharing class UpsertUnTaskREST {

    private static Map<String,String> productLineMap = new Map<String,String>();

    @HttpPost
    global static RestReturnMessage doPost(List<UnTaskBean> datas ) {
      RestReturnMessage message = null;
      try {
        productLineMap.put('迈可优产品', 'POCT');
        Map<String,List<UnTaskBean>> unMap =  new Map<String,List<UnTaskBean>>();
        Map<String,Account> accMap = new Map<String,Account>();
        for (UnTaskBean ut : datas ) {
          if(ut.minusTotal <=0 ) continue;
          String key = ut.accId +ut.company;
          List<UnTaskBean> tmp = unMap.containsKey(key)?unMap.get(key):new List<UnTaskBean>();
          tmp.add(ut);
          unMap.put(key, tmp);
          accMap.put(ut.accId, null);
        }

        Map<String,String>companyMap = ImportObject.getPicklistValues('ApplicationForUnqualifiedDelive__c', 'Company__c', false);
        //System.debug(companyMap);
        //助里与公司的对应:
        Map<String,String> assiMap =  new Map<String,String>();
         ///获取并验证助理是否在职

        Map<String,String> assistantMap = new Map<String,String>();
        for(String s : Label.NoteAssitant_UnqualifiedDelive.split(',') ){
          String[] ss =s.split('-'); 
          if(ss.size() > 0 )assistantMap.put(ss[0], ss[1]);
          assiMap.put(companyMap.get(ss[0]), ss[1]);  
        }
        
        for(User assi : [select Id ,Name,SubCompany__c ,IsActive from User where Id in: assistantMap.values() ] ){

          if(assi.IsActive != true  )throw new DmlException('有助理离职了请维护:Label.NoteAssitant_UnqualifiedDelive');
          if(!companyMap.containsKey(assi.SubCompany__c))throw new DmlException('请维护'+assi.SubCompany__c+'的公司编码到全局列表值!');

        }
        //查找客户销售员
         for(Account acc : [select Name,System__c ,Id,OwnerId ,Owner.IsActive,Owner.Profile.Name,Owner.SubCompany__c,IfMoreCompany__c ,NCICCode__c,RecordType.DeveloperName ,WhetherOpenBusiness__c, 
                  (select Id ,UserId,User.subcompany__c,User.IsActive,User.Profile.Name from AccountTeamMembers   )
                  from Account where Id in: accMap.keySet()]){
              accMap.put(acc.Id , acc);
            }

        
        Map<String,ApplicationForUnqualifiedDelive__c> mainTable = new Map<String,ApplicationForUnqualifiedDelive__c>();
        Map<String,List<ApplicationForUnqualifiedDeliveDetail__c>> detailTable = new Map<String,List<ApplicationForUnqualifiedDeliveDetail__c>>();
        String year = null;
        String quater = null;

        for (String key : unMap.keySet() ) {


          //匹配销售员
            //代开客户和 多 归口客户
          //如果归口公司==客户所有人的公司 则所有人
          //否则按产品线找 客户小组的销售员
          //如果产品线 没找到 则销售助理
          //如果为多归口 或者 代开票 则销售助理
          Integer i = 0;
          for (UnTaskBean ut  : unMap.get(key)) {
            Account acc = accMap.get(ut.accId );
            String OwnerId = null;
            String companycode = ut.company;
            if(acc.IfMoreCompany__c == true  ){

              OwnerId = assiMap.get(companycode);
            }else{//普通客户
                      OwnerId = companyMap.get(acc.Owner.SubCompany__c) == companycode ?(acc.Owner.IsActive ?  acc.OwnerId :null)  : getSalerId(companycode,acc ,companyMap);
                      if(OwnerId == null) OwnerId = assiMap.get(companycode);
                                  }
          if(OwnerId == null ){

            throw new DmlException('找不到对应的所有人!');

          }

          if(i ==0 ){
            ApplicationForUnqualifiedDelive__c apd = new ApplicationForUnqualifiedDelive__c();
              apd.OwnerId = OwnerId ; 
              apd.Company__c = ut.company;
              apd.Year__c = ut.year;
              apd.Quarter__c = ut.quater;
              apd.Account__c = ut.accId;
              apd.IfMoreCompany__c = acc.IfMoreCompany__c;

              apd.TaskMargin__c = ut.minusTotal;
              apd.TaskAchievementRate__c = ut.ritoTotal;
              apd.QuarterlyTaskVolume__c = ut.taskTotal;
              mainTable.put(key,apd );
              year = ut.year;
              quater = ut.quater;

          }
          List<ApplicationForUnqualifiedDeliveDetail__c> afList = detailTable.containsKey(key) ?detailTable.get(key) :new List<ApplicationForUnqualifiedDeliveDetail__c>();
          ApplicationForUnqualifiedDeliveDetail__c afdd = new ApplicationForUnqualifiedDeliveDetail__c();
          afdd.ProductLine__c = productLineMap.containsKey(ut.productLine) ? productLineMap.get(ut.productLine) : ut.productLine ;
          afdd.QuarterlyTaskVolume__c = ut.task;
          afdd.TaskAchievementRate__c = ut.rito;
          afdd.TaskMargin__c = ut.minus;
          afList.add(afdd);
          detailTable.put(key,afList);
          }
          
          
        }
        //已经存在的
        Map<String ,Id > apdMap = new Map<String,Id>();
        for(ApplicationForUnqualifiedDelive__c apd : [select Id,Account__c,Company__c from ApplicationForUnqualifiedDelive__c
         where Year__c =:year   and Quarter__c =: quater  and Account__c in:accMap.keySet() ] ){
          apdMap.put(apd.Account__c + apd.Company__c,apd.Id );
        }

         SavePoint sp = Database.setSavepoint();
         try {

           Set<Id> mainIds = new Set<Id>();

           for(ApplicationForUnqualifiedDelive__c apd : mainTable.values() ){
             String key = apd.Account__c+apd.Company__c ;
             if(apdMap.containsKey(key)){
               apd.Id = apdMap.get(key);
               mainIds.add(apd.Id);
             }
           }
           //清除已经存在 的明细
           delete [select Id from ApplicationForUnqualifiedDeliveDetail__c where ApplicationForUnqualifiedDelive__c in: mainIds ];

           upsert mainTable.values();
           List<ApplicationForUnqualifiedDeliveDetail__c> afList = new List<ApplicationForUnqualifiedDeliveDetail__c>();
           for ( String key : mainTable.keySet() ) {
             for(ApplicationForUnqualifiedDeliveDetail__c afdd : detailTable.get(key)){
               afdd.ApplicationForUnqualifiedDelive__c = mainTable.get(key).Id; 
               afList.add(afdd);
             }
           }
           insert afList;
             message = Utils.getRestReturnMessage(true,'保存成功！',new List<Map<String ,String>>());

         }catch (Exception e) {
             Database.rollback(sp);
             message = Utils.getRestReturnMessage(false,e.getMessage() + ' - ' + e.getStackTraceString()+Datetime.valueOf(Utils.MIN_DATE_TIME),new List<Map<String ,String>>());

         }
         
        

      }
      catch (Exception e) {
            message = Utils.getRestReturnMessage(false,e.getMessage() + ' - ' + e.getStackTraceString()+Datetime.valueOf(Utils.MIN_DATE_TIME),new List<Map<String ,String>>());

      }
      
        return message;
    }
    private static  Id getSalerId(String comcode ,Account acc,Map<String,String>cMap ){
      Id oId = null;
       Set<String> specialSet = new Set<String>{'系统管理员','销售部产品经理(集团)','销售管理部项目经理'};
      for(AccountTeamMember t : acc.AccountTeamMembers ){

        if(comcode == cMap.get(t.User.SubCompany__c)){
               if(specialSet.contains(t.User.Profile.Name) )continue;
                if(!t.User.IsActive)continue;
          oId = t.UserId ;
          break;
        }
      }
      return oId ;
    }


    global class UnTaskBean{

        public String productLine ;//产品线
        public Decimal task;//本季度任务量(万元)(产品线),
        public Decimal minus;//本年截止上季度任务量差额(万元)(产品线),
        public Decimal rito;//本年截止上季度任务量达成率(%)(产品线)
        public String company;//任务量归属公司,
        public String year;//季度,
        public String quater;//年度,
        public String accId;//开票客户名称,
        public Boolean isMore;//是否有多公司的任务量,
        public Decimal minusTotal;//本年截止上季度任务量差额(万元)(产品线汇总),
        public Decimal taskTotal;//本季度任务量(万元)(产品线汇总),
        public Decimal ritoTotal;//本年截止上季度任务量达成率(%)(产品线汇总)
        public String ncpk ;//客户档案主键

    }
}